package com.example.callloggenerator;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.List;

public class PermissionHelper {
    private static final int REQUEST_PERMISSION_CODE = 1;
    private static final int REQUEST_CODE = 1;
    private Activity activity;

    public PermissionHelper(Activity activity) {
        this.activity = activity;
    }

    // 检查并请求WRITE_CALL_LOG权限
    public void checkPermissions() {
        String[] permissions = {
                Manifest.permission.WRITE_CALL_LOG,
                Manifest.permission.READ_PHONE_STATE
        };

        List<String> deniedPermissions = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(activity, permission)
                    != PackageManager.PERMISSION_GRANTED) {
                deniedPermissions.add(permission);
            }
        }

        if (!deniedPermissions.isEmpty()) {
            ActivityCompat.requestPermissions(activity,
                    deniedPermissions.toArray(new String[0]),
                    REQUEST_CODE);
        }
    }

    // 处理权限请求结果
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CODE) {
            boolean allGranted = true;
            for (int result : grantResults){
                if (result != PackageManager.PERMISSION_GRANTED){
                    allGranted = false;
                    break;
                }
            }
            Toast.makeText(activity, allGranted ? "权限获取成功" : "权限获取失败", Toast.LENGTH_SHORT).show();
        }
    }
}
